package com.study.concurrent.A_ThreadManagement.j_ThreadGroup;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by 赵超 on 2017/3/19.
 */
public class SearchTask implements Runnable {
    private Result result;

    public SearchTask(Result result) {
        this.result = result;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.printf("线程 %s: 开始\n", name);
        try {
            doTask();
            result.setName(name);
        } catch (InterruptedException e) {
            System.out.printf("线程 %s: 中断\n", name);
            return;
        }
        System.out.printf("线程 %s: 结束\n", name);
    }

    /**
     * 用它创建Random对象来生成一个随机数，并使用它作为参数调用sleep()方法
     * @throws InterruptedException
     */
    private void doTask() throws InterruptedException {
        Random random = new Random(new Date().getTime());
        int value = (int) (random.nextDouble() * 100);
        System.out.printf("线程 %s : %d\n", Thread.currentThread().getName(), value);
        TimeUnit.SECONDS.sleep(value);
    }
}
